import express from 'express'
import { faker } from '@faker-js/faker'
import cors from 'cors'

const app = express()
const PORT = 3000

// 定义商品接口
// interface Product {
//   id: number
//   name: string
//   price: number
//   category: string
//   description: string
//   image: string
// }

// 生成模拟商品数据的函数
function generateProducts(count) {
  const products = []

  for (let i = 0; i < count; i++) {
    products.push({
      id: i + 1,
      name: faker.commerce.productName(),
      price: parseFloat(faker.commerce.price()),
      category: faker.commerce.department(),
      description: faker.commerce.productDescription(),
      image: faker.image.urlPicsumPhotos(),
    })
  }

  return products
}

// 中间件
app.use(cors())
app.use(express.json())

// 分页商品列表接口
app.post('/api/products', (req, res) => {
  const { page = 1, pageSize = 50 } = req.body

  // 生成100万条数据
  const totalProducts = 1000000
  const allProducts = generateProducts(totalProducts)

  // 计算分页
  const startIndex = (page - 1) * pageSize
  const endIndex = startIndex + pageSize
  const paginatedProducts = allProducts.slice(startIndex, endIndex)

  res.json({
    total: totalProducts,
    page,
    pageSize,
    data: paginatedProducts,
  })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`)
})
